﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Table;

namespace UploadProductImageApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var dctx = new MY_DB_ON_CLOUDEntities();

            var data = dctx.ProductSet.ToList();
            dataGridView1.DataSource = data;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                var id = Convert.ToInt32(
                    dataGridView1.SelectedRows[0].Cells[0].Value);

                if (openFileDialog1.ShowDialog(this)
                    == System.Windows.Forms.DialogResult.OK)
                {
                    var fullpath = openFileDialog1.FileName;
                    var fname = System.IO.Path.GetFileName(fullpath);
                    // TODO: Upload
                    var connectionString =
                        @"DefaultEndpointsProtocol=https;AccountName=cloudsipa2012;AccountKey=RzXlHysriinWJHoM7nuq05dlGDxKcbuXveHY9peqcdhIO+k38g3zMi9xB5sNLUgbBOL3G+vCz3fT9RUV72vb8w==";

                    var storageAccount = CloudStorageAccount.Parse(
                        connectionString);
                    // BLOB specific
                    var blobClient = storageAccount.CreateCloudBlobClient();

                    var container = blobClient.GetContainerReference("demo");
                    container.CreateIfNotExists();

                    var blob = container.GetBlockBlobReference(fname);
                    using (var fileSteam = openFileDialog1.OpenFile())
                    {
                        blob.Properties.ContentType = "image/jpeg";
                        blob.UploadFromStream(fileSteam);
                        blob.FetchAttributes();
                        blob.Metadata.Add("ProductId", id.ToString());
                        blob.SetMetadata();
                    }

                    // SQL Azure only
                    var dctx = new MY_DB_ON_CLOUDEntities();
                    var product = dctx.ProductSet
                        .Where(it => it.Id == id).FirstOrDefault();
                    product.ImageUrl = blob.Uri.AbsoluteUri;
                    dctx.SaveChanges();

                    MessageBox.Show(openFileDialog1.FileName +
                        " has been uploaded to " + id);

                    // TABLE specific
                    var tableClient = storageAccount.CreateCloudTableClient();
                    var table = tableClient.GetTableReference("uploadinfo");
                    table.CreateIfNotExists();

                    var uploadInfo = new UploadInfo
                    {
                        PartitionKey = "Product Images",
                        RowKey = string.Format("{0:D19}", DateTime.Now.Ticks),

                        LocalPath = fullpath,
                        ImageUrl = blob.Uri.AbsoluteUri,
                        UploadDateTime = DateTime.Now,
                    };

                    var insertOperation = TableOperation.Insert(uploadInfo);
                    table.Execute(insertOperation);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var form = new CatForm();
            form.Show(this);
        }
    }
}
